package com.zkas.canalefectivo.datasyncro;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.util.Log;
//import com.google.common.base.Splitter;
//import com.google.common.collect.Iterables;
import com.zkas.canalefectivo.xmlparsing.XMLParser;

import android.content.Context;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;

import java.util.ArrayList;
import java.util.HashMap;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class WebServiceClient implements DataSource {
	
	
	/* esto en la notebook. 
	private final String IP = "192.168.1.101";  // 192.168.1.101
			
	private final String NAMESPACE = "http://tempuri.org/";
	private final String URL = "http://" + IP + "/WebService/WebService1.asmx";
	//private final String URL = IP + "/WebService/WebService1.asmx";
	private final String SOAP_ACTION = "http://tempuri.org/getClientData";
	private final String METHOD_NAME = "getClientData";
	*/
	/* esta es la dire real.*/
	private final String NAMESPACE = "http://www.superpagoonline.com/";
							   //"http://www.superpagoonline.com/ws/superpagows.asmx"							 	
	private final String URL = "http://www.superpagoonline.com/ws/superpagows.asmx";
	private final String METHOD_LOGIN = "DoLogin";
	private final String METHOD_GETFAC = "Factura_Get";
	private final String SOAP_ACTION = "http://www.superpagoonline.com/";
	
	static final String KEY_ITEM = "Factura"; // parent node
	static final String KEY_ID = "Iden";
	static final String KEY_NAME = "Entidad";
	static final String KEY_CASH = "Importe";
	static final String KEY_SERV = "Servicio";
	static final String KEY_DATE = "Vencimiento";
	
	ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
	
	@Override
	public ArrayList<HashMap<String, String>> getBillsFromServer(String user) {
                
        //TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        //GsmCellLocation location = (GsmCellLocation) tm.getCellLocation();
        //String IMEI = tm.getDeviceId();
        //int lac = location.getLac();
        
        // aca cambiar por usuario y password.
        //String user = "marcebil@gmail.com";	
        String pwd = "marcelo1";
        
        //if (validateUser(user, pwd))	// no funca
        //{
        	return getData(user);
        //}
		//return null;
	}
	
	private boolean validateUser(String user, String pwd)
	{
        SoapObject request = new SoapObject(NAMESPACE, METHOD_LOGIN); 
		
		PropertyInfo usrInfo =new PropertyInfo();
		usrInfo.setName("usu_mail");
		usrInfo.setValue(user);
		usrInfo.setType(String.class);
        request.addProperty(usrInfo);

        PropertyInfo pwdInfo =new PropertyInfo();
		pwdInfo.setName("usu_password");
		pwdInfo.setValue(pwd);
		pwdInfo.setType(String.class);
        request.addProperty(pwdInfo);
           	 	
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.dotNet = true;
		envelope.setOutputSoapObject(request);
		HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

		try {
			androidHttpTransport.call(SOAP_ACTION+METHOD_LOGIN, envelope);
			SoapObject response = (SoapObject) envelope.getResponse();				// esto para afuera
			//SoapPrimitive response = (SoapPrimitive)envelope.getResponse();				// esto con webserver zk

			Log.i("myApp", response.toString());
			
			PropertyInfo pi = new PropertyInfo();
            response.getPropertyInfo(0, pi);
			if (pi.name.equals("Error"))
			{
				return true;  // aca deberia retornar false...
			}
			else
			{
				return true;
			}		
		} catch (Exception e) {
			if (e != null)
				e.printStackTrace();
			return false;
		}	
	}
	
	private ArrayList<HashMap<String, String>> getData(String user)
	{
		SoapObject request = new SoapObject(NAMESPACE, METHOD_GETFAC); 
		PropertyInfo usrInfo =new PropertyInfo();
		usrInfo.setName("usu_mail");
		usrInfo.setValue(user);
		usrInfo.setType(String.class);
        request.addProperty(usrInfo);		        

        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.dotNet = true;
		envelope.setOutputSoapObject(request);
		HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
		androidHttpTransport.debug=true; 
			//anyType{Factura=anyType{Entidad=Empresa Demo S.A.; Servicio=Cuota Prepaga; Iden=000100012345; Vencimiento=30/01/2013; Importe=350; }; Factura=anyType{Entidad=River Plate; Servicio=Cuota Social; Iden=000100032123; Vencimiento=10/05/2013; Importe=105,49; }; }
		try {
	        androidHttpTransport.call(SOAP_ACTION+METHOD_GETFAC, envelope);
	        SoapObject response = (SoapObject) envelope.getResponse();				// esto para afuera

	        String responseXML = "";
	        responseXML = androidHttpTransport.responseDump;
			Log.d("Response in XML", responseXML);
			androidHttpTransport.debug=false;

			//String xml = parser.getXmlFromUrl(URL); // getting XML
			XMLParser parser = new XMLParser();			
			Document doc = parser.getDomElement(responseXML); // getting DOM element
			NodeList nl = doc.getElementsByTagName(KEY_ITEM);
			for (int i = 0; i < nl.getLength(); i++) {
				// creating new HashMap
				HashMap<String, String> map = new HashMap<String, String>();
				Element e = (Element) nl.item(i);
				// adding each child node to HashMap key => value
				map.put(KEY_ID, parser.getValue(e, KEY_ID));
				map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
				map.put(KEY_CASH, parser.getValue(e, KEY_CASH));	// que es Rs.? Real?
				map.put(KEY_SERV, parser.getValue(e, KEY_SERV));
				map.put(KEY_DATE, parser.getValue(e, KEY_DATE));

				// adding HashList to ArrayList
				menuItems.add(map);
			}
			
			return menuItems;
			/*
			String[] data = response.toString().split("#");
			
			String[] cashed =
				    Iterables.toArray(
				        Splitter
				            .fixedLength(104)
				            .split(data[0]),
				        String.class
				    );
			
			String[] toCash =
				    Iterables.toArray(
				        Splitter
				            .fixedLength(104)
				            .split(data[1]),
				        String.class
				    );
			
			//TextView tv = new TextView(this);
		    //tv.setText("Cel number: " + celNumber + "  pagadas "+pagadas.length + " apagar: " + apagar.length);
		    //setContentView(tv);
			Log.i("myApp", "Usuario: " + user + "  pagadas: "+cashed.length + ", apagar: " + toCash.length);
			return (toCash);
			*/
		}		
		catch (Exception e) {
			e.printStackTrace();
		}		
		return null;
	}
}
